import { app } from '../../../../../../../../app/app';
import { EcsSystem, NodeComponent, filter } from '../../../../../../../../pkg-export/@gamex/cc-ecs';
import { DestroyComponent } from '../component/DestroyComponent';
import { EnemyComponent } from '../component/EnemyComponent';
import { PlayerComponent } from '../component/PlayerComponent';

export class ShootSystem extends EcsSystem {
    private playerFilter = filter.all(PlayerComponent, NodeComponent);
    private enemyFilter = filter.all(EnemyComponent).exclude(DestroyComponent);

    private pause = 0;
    private shootIntervalMap: Map<EnemyComponent, number> = new Map();

    protected execute(dt: number): void {
        
        this.handleShoot(dt);
        
        const enemyEntitys = this.query(this.enemyFilter);
        for (const enemyEntity of enemyEntitys) {
            const enemyComp = enemyEntity.get(EnemyComponent);
            if (!enemyComp.canShoot) continue;
            if (this.shootIntervalMap.has(enemyComp)) {
                
                if (this.shootIntervalMap.get(enemyComp) + dt > enemyComp.interval) {
                    this.shootIntervalMap.set(enemyComp, 0);
                    app.controller.game.enemyShoot(enemyComp);
                } else {
                    this.shootIntervalMap.set(enemyComp, this.shootIntervalMap.get(enemyComp) + dt);
                }
            } else {
                this.shootIntervalMap.set(enemyComp, 0);
                app.controller.game.enemyShoot(enemyComp);
            }
            
        }

    }

    handleShoot(dt: number) {
        const playerEntity = this.find(this.playerFilter);
        if (!playerEntity) return;

        this.pause -= dt;
        if (this.pause > 0) return;

        const node = playerEntity.get(NodeComponent);
        const player = playerEntity.get(PlayerComponent);
        this.pause = player.interval;

        app.controller.game.shoot(node, player);
    }
}

